import { login, logout ,smsCodeLogin } from '@/api'
import { getToken, setToken, removeToken } from '@/utils/auth'

const user = {
  state: {
    token: getToken(),
    name: '',
    avatar: '',
    roles:null,
    mobile:'',
    sellerId:'',
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLE: (state, roles) => {
      state.roles = roles;
    },
    SET_SELLERID: (state, id) => {
      state.sellerId = id;
    },
    SET_MOBILE:(state, mobile) =>{
      state.mobile = mobile
    }
  },

  actions: {
    // 登录
    Login({ commit }, param) {
      const username = param.data.username.trim()
      return new Promise((resolve, reject) => {

          login(username, param.data.password).then(response => {
            const data = response;
            const tokenStr = 'Bearer '+data;
            setToken(tokenStr)
            commit('SET_TOKEN', tokenStr);
            resolve()
          }).catch(error => {
            reject(error)
          })
      })
    },


    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        const data = localStorage.getExpire('userInfo');
        if (data && data.isEnableBackend) { // 验证返回用户信息是否有值
          console.log("有值")
          commit('SET_SELLERID', data.user_id);
          commit('SET_ROLE', data.roles);
          commit('SET_NAME', data.buyer_realname);
          commit('SET_AVATAR', data.icon);
          commit('SET_MOBILE',data.username);
          resolve(data)
        } else {
          console.log("错误")
          reject('getInfo: roles must be a non-null array !')
        }
      })
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        // logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', '')
          removeToken()
          resolve()
        // }).catch(error => {
        //   reject(error)
        // })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '');
        localStorage.clear();
        removeToken();
        resolve()
      })
    }
  }
}

export default user
